package com.saas.ability.gateway.provider;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.saas.ability.core.base.constant.retcode.RetCode;
import com.saas.ability.core.base.protocol.SimpleOutput;

@Component
public class ServantProvider implements FallbackProvider {
	
	Logger logger = LoggerFactory.getLogger(ServantProvider.class);

	@Override
	public String getRoute() {
		return "*";
	}

	@Override
	public ClientHttpResponse fallbackResponse() {
		logger.error("===========网关转发服务请求不成功================");
		return getClientHttpResponse(new Throwable("转发服务请求不成功,服务降级处理"));
	}

	@Override
	public ClientHttpResponse fallbackResponse(Throwable cause) {
		logger.error("===========网关转发服务请求不成功=================",cause);
		return getClientHttpResponse(cause);
	}
	
	private ClientHttpResponse getClientHttpResponse(Throwable cause){
		return new ClientHttpResponse() {

			@Override
			public HttpHeaders getHeaders() {
				HttpHeaders headers = new HttpHeaders();
				headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
				return headers;
			}

			@Override
			public InputStream getBody() throws IOException {
				SimpleOutput output = null;
				if(cause != null){
					output = new SimpleOutput(RetCode.FAIL.retCode, "服务器开小差,服务调度不成功,cause:" + cause.getMessage());
				}else{
					output = new SimpleOutput(RetCode.FAIL.retCode, "服务器开小差,服务调度不成功");
				}
				return new ByteArrayInputStream(JSON.toJSONString(output).getBytes("UTF-8"));
			}

			@Override
			public String getStatusText() throws IOException {
				return HttpStatus.OK.getReasonPhrase();
			}

			@Override
			public HttpStatus getStatusCode() throws IOException {
				return HttpStatus.OK;
			}

			@Override
			public int getRawStatusCode() throws IOException {
				return HttpStatus.OK.value();
			}

			@Override
			public void close() {
				logger.info("===========close=================");
			}
		};
	}

}
